﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.CodeDom;
using System.CodeDom.Compiler;

namespace _0512063_0512082
{
    class CodeRunner
    {
        private CodeDomProvider provider;
        private String sourceCode;
        private String exeFile;
        private Boolean canExecute;

        public Boolean CanExecute
        {
            get { return canExecute; }
            set { canExecute = value; }
        }
       
        public CodeRunner(CodeDomProvider codeProvider, String sourse, String destination)
        {
            provider = codeProvider;
            sourceCode = sourse;
            exeFile = destination;
            canExecute = false;
                
        }

        /// <summary>
        /// MSDN ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_system/html/f7f9984e-0748-1a59-2e1d-605b5e332b3a.htm#exampleToggle
        /// </summary>
        /// <returns></returns>
        public String Compile()
        {
            String compileresult = "";            
            ICodeCompiler myCodeCompiler = provider.CreateCompiler();
            String[] referenceAssemblies = { "System.dll" };
            CompilerParameters cp = new CompilerParameters(referenceAssemblies,exeFile);
            cp.GenerateExecutable = true;
            
            // invoke compile
            CompilerResults cr = myCodeCompiler.CompileAssemblyFromSource(cp, sourceCode);
            if (cr.Errors.Count > 0)
            {
                canExecute = false;
                               
                foreach (CompilerError ce in cr.Errors)
                {
                    compileresult += String.Format("  {0}", ce.ToString());
                    compileresult += "\r\n";
                }
            }
            else
            {
                canExecute = true;
                compileresult = String.Format(MainForm.RM.GetString("CompileSuccess"));
            }

            return compileresult;
        }

        public void Run()
        {
            try
            {
                System.Diagnostics.Process.Start(exeFile);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}
